package com.hpin.fansea.ui;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.hpin.fansea.R;
import com.hpin.fansea.adapter.CommunityListAdapter;
import com.hpin.fansea.base.BaseActivity;
import com.hpin.fansea.bean.ChooseCommunity;
import com.hpin.fansea.bean.Community;
import com.hpin.fansea.bean.ResultBaseBean;
import com.hpin.fansea.utils.CommonUtils;
import com.hpin.fansea.utils.Constant;
import com.hpin.fansea.utils.HttpUtil;
import com.lidroid.xutils.http.RequestParams;

import java.util.ArrayList;
import java.util.List;

/**
 * 选择小区页面
 * Created by Aaron on 15/9/8.
 */
public class FirstCommunitySelectActivity extends BaseActivity {

    private ListView lv_community;
    private CommunityListAdapter communityListAdapter;
    private List<Community> communityArray = new ArrayList<Community>();

    private String userId;
    private String communityId;
    private String communityName;

    private String cityId;
    private String cityName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_community_select);

        mApplication.addActivity(this);

        cityId = getIntent().getStringExtra("cityId");
        cityName = getIntent().getStringExtra("cityName");

        initView();

        initCommunityData();

    }

    /**
     * 加载小区信息
     */
    private void initCommunityData() {

        HttpUtil.getInstance().setGetRequest("获取中...", this,
                Constant.WEB_ROOT + Constant.HOUSESERVICE + cityId + Constant.PROJECTLIST, new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {

                        try {

                            ChooseCommunity chooseCommunity = JSONObject.parseObject(str, ChooseCommunity.class);

                            if (Constant.STATUS_SUCESS.equals(chooseCommunity.status)) {

                                communityArray= chooseCommunity.result;
                                communityListAdapter.setDate(communityArray);
                                communityListAdapter.notifyDataSetChanged();

                            }else {
                                showToast(chooseCommunity.message);
                            }

                        }catch (Exception e) {
                            e.printStackTrace();
                            showToast("获取小区信息失败");
                        }
                    }
                }, null);

    }

    private String fmpic;
//    private int currentPostion;

    private void initView() {

        TextView tv_left = (TextView) findViewById(R.id.tv_left);
        TextView tv_title = (TextView) findViewById(R.id.tv_title);

        tv_title.setText(getResources().getString(R.string.community));

        tv_left.setOnClickListener(this);

        lv_community = (ListView) findViewById(R.id.lv_community_first);
        communityListAdapter = new CommunityListAdapter(this, communityArray);
        lv_community.setAdapter(communityListAdapter);

        lv_community.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {

                sp = getSharedPreferences(Constant.CONFIG, MODE_PRIVATE);

                userId = sp.getString(Constant.userId, "");
                communityId = communityArray.get(arg2).projectId;
                communityName = communityArray.get(arg2).projectName;
//                currentPostion = arg2;
                if (CommonUtils.isNetworkAvailable(FirstCommunitySelectActivity.this)) {
                    // 判断登录状态是游客
                    fmpic = communityArray.get(arg2).fmpic;


                    /*
                    Map<String, Object> params = new HashMap<String, Object>();
		params.put("systemType", SYSTEM_TYPE);
		params.put("token", Constant.token);
		params.put("loginType", loginType);
		params.put("userId", phone);

		String res = HttpUtil.httpPost(WEB_ROOT + "loginCommunityService/"
				+ communityId, params);
                     */

                    RequestParams params = new RequestParams();
                    params.addBodyParameter("systemType", Constant.SYSTEM_TYPE);
                    params.addBodyParameter("token", sp.getString(Constant.token, ""));
                    params.addBodyParameter("loginType", Constant.INTERFACE_USERTYPE_NORMAL);
                    params.addBodyParameter("userId", userId);

                    HttpUtil.getInstance().setPostRequest("获取中...", FirstCommunitySelectActivity.this,
                            Constant.WEB_ROOT + Constant.COMMUNITYSERVICE + communityId, params, new HttpUtil.SuccessListener() {
                                @Override
                                public void setOnSuccessListener(String str) {

                                    try {

                                        ResultBaseBean resultBaseBean = JSONObject.parseObject(str, ResultBaseBean.class);

                                        if (Constant.STATUS_SUCESS.equals(resultBaseBean.status)) {

                                            SharedPreferences.Editor edit = sp.edit();
                                            //保存小区数据
                                            edit.putString(Constant.communityId, communityId);
                                            edit.putString(Constant.communityName, communityName);
                                            edit.putString(Constant.status, resultBaseBean.userStatus);
                                            edit.putString(Constant.cityId, cityId);
                                            edit.putString(Constant.cityName, cityName);
                                            edit.commit();

                                            Intent intent = new Intent(FirstCommunitySelectActivity.this,
                                                    HomeActivity.class);
                                            startActivity(intent);

//                                            mApplication.clearActivity();

                                        }else {
                                            showToast(resultBaseBean.message);
                                        }


                                    }catch (Exception e) {
                                        e.printStackTrace();
                                        showToast("设置小区失败");
                                    }

                                }
                            }, null);

//                    DataService.loginFirstSelect(context, handler, userId,
//                            communityId,
//                            Constant.STATUS_VISITOR.equals(sp.getString(Constant.status,""))?Constant.INTERFACE_USERTYPE_VISITOR:Constant.INTERFACE_USERTYPE_NORMAL);
                } else {
                    showToast(Constant.NETWORK_EXCEPTION_ERROR);
                }

            }
        });

    }

//    private Handler handler = new Handler() {
//
//        @Override
//        public void handleMessage(Message msg) {
//            ResultEntity ro = (ResultEntity) msg.obj;
//            if (ro == null) {
//                // showToast("服务器异常");
//                return;
//            }
//            switch (msg.what) {
//                case MessageDefine.COMMUNITY_LIST:
//                    if (ro.getStatus().equals("1000100030001")) {
//                        communityArray = JSONArray.parseArray(ro.getResult(),
//                                Community.class);
//                        communityListAdapter.setDate(communityArray);
//                        communityListAdapter.notifyDataSetChanged();
//                    } else {
//                        dismissProgress();
//                        showToast(ro.getMessage());
//                    }
//                    break;
//                case MessageDefine.LOGIN_FIRST:
//                    // 首次选择小区
//                    if (ro.getStatus().equals("1000100030001")) {
//                        LogUtil.e("login", "LOGIN_FIRST---chenggong");
//                        // /////////////////
//                        // 第一次登录存小区-----切换小区
//                        // id
//                        application.userInfoByLogin.setCommunityId(communityId);
//                        // name
//                        application.userInfoByLogin.setCommunityName(communityName);
//                        Constant.communityName = communityName;
//                        Constant.COMMUNITY_ID = communityId;
//                        userInfo.setCommunityId(communityId);
//                        userInfo.setCommunityName(communityName);
//                        //设置登陆状态
//                        userInfo.setStatus(ro.getUserStatus());
//                        application.userInfoByLogin.setStatus(ro.getUserStatus());
//                        Constant.currentStatus = ro.getUserStatus();
//
//                        editor.putString("communityId", communityId);
//                        editor.commit();
//                        // 如果是金泽大厦 则调启动页
//                        if (Constant.communityName.equals(Constant.JinZe)) {
//                            ApplicationEx.getInstance().exitTemp();
//                            Intent intent = new Intent(
//                                    FirstCommunitySelectActivity.this,
//                                    StartPurchaseActivity.class);
//
//                            intent.putExtra("pic", fmpic);
//
//                            startActivity(intent);
//                            finish();
//                        } else {
//                            ApplicationEx.getInstance().exitTemp();
//                            Intent intent = new Intent(
//                                    FirstCommunitySelectActivity.this,
//                                    HomeActivity.class);
//                            startActivity(intent);
//                            finish();
//                        }
//                    } else {
//                        dismissProgress();
//                        LogUtil.e("login", "login-error-message" + ro.getMessage());
//                        showToast(ro.getMessage());
//                    }
//                    break;
//                default:
//                    break;
//            }
//        }
//
//    };

    @Override
    public void widgetClick(View v) {

        switch (v.getId()) {
            case R.id.tv_left:
                finish();
                break;
        }
    }

}